package main

import (
	"fmt"
	"zinx/ziface"
	"zinx/znet"
)

// ping test 自定义路由
type HelloRouter struct {
	znet.BaseRouter
}

// 模版方法设计模式

// Test Handle
func (r *HelloRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call  Hello Router Handle ....")
	// 先读取客户端的数据，再会写ping....ping...
	fmt.Println("recv from client: msgID = ", request.GetMsgId(), ", data = ", string(request.GetData()))
	err := request.GetConnection().SendMsg(200, []byte("hello....hello...hello..."))
	if err != nil {
		fmt.Println(err)
	}
}

// ping test 自定义路由
type PingRouter struct {
	znet.BaseRouter
}

// 模版方法设计模式

// Test Handle
func (r *PingRouter) Handle(request ziface.IRequest) {
	fmt.Println("Call Ping Router Handle ....")
	// 先读取客户端的数据，再会写ping....ping...
	fmt.Println("recv from client: msgID = ", request.GetMsgId(), ", data = ", string(request.GetData()))
	err := request.GetConnection().SendMsg(201, []byte("ping....ping...ping..."))
	if err != nil {
		fmt.Println(err)
	}
}

// 链接链接之后要执行的函数
func DoConnectionBegin(conn ziface.IConnection) {
	fmt.Println("====> DoConnectionBegin is called......")
	if err := conn.SendMsg(202, []byte("=====DoConnectionBegin is called========")); err != nil {
		fmt.Println(err)
	}
	// 给当前的链接设置一些属性
	fmt.Println("Set conn property.......")
	conn.SetProperty("name", "jason ddddddd")
	conn.SetProperty("Github", "https://www.github.com/xxxxx")
	conn.SetProperty("home", "ccccccccccc")
	conn.SetProperty("jianshu", "https://jianshu.com/u/12312312")
}

// 链接断开之前的需要执行的函数
func DoConnectionLost(conn ziface.IConnection) {
	fmt.Println("====> DoConnectionLost is called......")
	fmt.Println("==== conn id=", conn.GetConnID(), " is lost========")

	//获取链接属性
	if name, err := conn.GetProperty("name"); err == nil {
		fmt.Println("name == > ", name)
	}
	if github, err := conn.GetProperty("Github"); err == nil {
		fmt.Println("Github == > ", github)
	}

	// 删除链接属性
	conn.RemoveProperty("home")
	if home, err := conn.GetProperty("home"); err == nil {
		fmt.Println("home == > ", home)
	} else {
		fmt.Println("home is removed ")
	}
}

func main() {
	s := znet.NewServer("[zinx V0.10]")
	// 注册链接Hook钩子函数
	s.SetOnConnStart(DoConnectionBegin)
	s.SetOnConnStop(DoConnectionLost)
	// 添加路由
	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &HelloRouter{})
	s.Serve()
}
